package demo;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileSystemDemo {
    private FileSystem fs;

    @Before
    public void init() throws Exception {
        // 构造一个配置参数对象，设置一个参数：要访问的HDFS的URI
        Configuration conf = new Configuration();
        // 指定使用HDFS访问
        conf.set("fs.default.name", "hdfs://localhost:9001");
        // 进行客户端身份的设置(root为虚拟机的用户名，hadoop集群节点的其中一个都可以)
        System.setProperty("HADOOP_USER_NAME", "root");
        // 通过FileSystem的静态get()方法获取HDFS文件系统客户端对象
        fs = org.apache.hadoop.fs.FileSystem.get(conf);
    }

    @After
    public void close() throws IOException {
        //关闭资源
        fs.close();
    }

    /**
     * 上传
     *
     * @throws IOException
     */
    @Test
    public void upload() throws IOException {
        fs.copyFromLocalFile(new Path("C:\\Users\\Administrator\\Desktop\\temp2.txt"), new Path("/code1"));
    }

    /**
     * 下载
     */
    @Test
    public void downLoad() throws IOException {
        File file = new File("E:\\temp\\3.txt");
        Path ds = new Path("/temp/text/3");
        FSDataInputStream open = fs.open(ds);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] bytes = new byte[1024];
        int readData = 0;
//        open.get
        while ((readData = open.read(bytes)) != -1) {
            fileOutputStream.write(bytes, 0, readData);
        }
        fileOutputStream.close();
        open.close();
    }

    /**
     * 删除
     */
    @Test
    public void delete() throws IOException {
        Path ds = new Path("/code1");
        /*
         *  第二个参数代表是否递归删除
         *    +  如果 path 是一个目录且递归删除为 true, 则删除该目录及其中所有文件;
         *    +  如果 path 是一个目录但递归删除为 false,则会则抛出异常。
         */
        boolean delete = fs.delete(ds, false);
        System.out.println("删除结果为：" + delete);
    }


    /**
     * 创建目录
     */
    @Test
    public void mkdir() throws IOException {
        Path path = new Path("/temp/testFile");
        boolean mkdirs = fs.mkdirs(path);
        System.out.println(mkdirs);
    }

    /**
     * 检查文件或者目录是否存在
     */
    @Test
    public void checkExists() throws IOException {
        Path path = new Path("/music2");
        boolean exists = fs.exists(path);
        System.out.println(exists);
    }


    /**
     *得到目录文件的各种信息
     */
    @Test
    public void status() throws IOException {
        FileStatus[] fileStatuses = fs.listStatus(new Path("/temp"));
        for (FileStatus fileStatus : fileStatuses) {
            String s = fileStatus.getPath().toString();
            System.out.println(s);
        }
    }
}
